﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using PMS.BusinessFacade;
using PMS.EntityManage;
using PMS.Common;
using PMS.EntityQuery;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Text;
using EntityManage;

public partial class Modules_Personal_PerfApplyApprove : System.Web.UI.Page
{
    IPerf_Personal_ApprovalHandler approvalHandler = new Perf_Personal_ApprovalManage();
    ISys_UserHandler userHandler = new Sys_UserManage();
    ISys_OrganizationHandler orgHandler = new Sys_OrganizationManage();
    ISys_PostHandler postHandler = new Sys_PostManage();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!CheckPurviews())
        {
            Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            ViewState["OrderBy"] = "Status";
            ViewState["Accending"] = "asc";

            dataBind(string.Empty, null);
          
        }
    }

    private bool CheckPurviews()
    {
        if (Session["UserPurviews"] != null)
        {
            string strPur = Session["UserPurviews"].ToString();
            if (strPur.Contains("303030"))
            {
                
            }
            else
            {
                return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }

    #region DataBind
    
    /// <summary>
    /// 初始化岗位信息表
    /// </summary>
    private void dataBind(string whereClause, SqlParameter[] parms)
    {
        try
        {
            FillSearchDDL();

            int counter = 0;
            DataTable dt = new DataTable();

            #region 读取与登录用户有关的流程步骤ID，根据这些ID来读取与登录用户有关的记录

            int userId = int.Parse(Session["CurrentUserID"].ToString());
            string businessIds = FlowTrace.GetUserCurrentFlowBusinessIds(userId, (int)Enums.PerfFlowIDs.PersonalEvaluateApproval);

            whereClause = " ID in (" + businessIds + ")" + (whereClause == string.Empty ? "" : (" and " + whereClause));
           
            #endregion

            dt = approvalHandler.GetPerf_Personal_ApprovalByPageList(whereClause, parms, ViewState["OrderBy"].ToString() + " " + ViewState["Accending"].ToString(), AspNetPager.StartRecordIndex - 1, AspNetPager.PageSize);

            counter = approvalHandler.GetCounter(whereClause, parms);

            this.AspNetPager.RecordCount = counter;
            gvPerfApproveList.DataSource = dt;
            gvPerfApproveList.DataBind();
        }
        catch
        {
            Jscript.AlertInAjax("連接錯誤!", UpdatePanel1);
            return;
        }
    }

    public string GetTotalScore(object score, object taskScore, object pluseScore)
    {
        return Convert.ToString(double.Parse(score.ToString()) + double.Parse(taskScore.ToString()) + double.Parse(pluseScore.ToString()));
    }

    /// <summary>
    /// 条件参数处理
    /// </summary>
    /// <param name="whereClause"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string whereClause, ref SqlParameter[] parms)
    {
        List<SqlParameter> lstParm = new List<SqlParameter>();

        if (ViewState["SearchPerfDate"] != null)
        {
            whereClause += " and Perf_Date = @Perf_Date";
            lstParm.Add(new SqlParameter("@Perf_Date", ViewState["SearchPerfDate"].ToString()));
        }
        if (ViewState["SearchStatus"] != null)
        {
            whereClause += " and Status = @Status";
            lstParm.Add(new SqlParameter("@Status", int.Parse(ViewState["SearchStatus"].ToString())));
        }

        parms = lstParm.ToArray();
    }

    private void FillSearchDDL()
    {
        FillStatus();
    }

    private void FillStatus()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name");
        dt.Columns.Add("Value");
        DataRow dr;

        dr = dt.NewRow();
        dr["Name"] = "全部";
        dr["Value"] = 0;
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["Name"] = Enums.GetPersonalApprovalStatus(Enums.PersonalApprovalStatus.NewAdded);
        dr["Value"] = (int)Enums.PersonalApprovalStatus.NewAdded;
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["Name"] = Enums.GetPersonalApprovalStatus(Enums.PersonalApprovalStatus.Passed);
        dr["Value"] = (int)Enums.PersonalApprovalStatus.Passed;
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["Name"] = Enums.GetPersonalApprovalStatus(Enums.PersonalApprovalStatus.Notice);
        dr["Value"] = (int)Enums.PersonalApprovalStatus.Notice;
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["Name"] = Enums.GetPersonalApprovalStatus(Enums.PersonalApprovalStatus.Archive);
        dr["Value"] = (int)Enums.PersonalApprovalStatus.Archive;
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["Name"] = Enums.GetPersonalApprovalStatus(Enums.PersonalApprovalStatus.NotPassed);
        dr["Value"] = (int)Enums.PersonalApprovalStatus.NotPassed;
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["Name"] = Enums.GetPersonalApprovalStatus(Enums.PersonalApprovalStatus.Invalid);
        dr["Value"] = (int)Enums.PersonalApprovalStatus.Invalid;
        dt.Rows.Add(dr);

        ddlStatus.DataTextField = "Name";
        ddlStatus.DataValueField = "Value";
        ddlStatus.DataSource = dt;
        ddlStatus.DataBind();
    }

    #endregion

    #region gvPerfApproveList

    protected void gvPerfApproveList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        
    }

    protected void gvPerfApproveList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            HtmlInputCheckBox chkSelected = (HtmlInputCheckBox)e.Row.FindControl("chkSelected");
            if (int.Parse(e.Row.Cells[8].Text.Trim()) == (int)Enums.PersonalApprovalStatus.NewAdded)
                chkSelected.Visible = true;
            else
                chkSelected.Visible = false;

            if (e.Row.RowIndex > -1)
            {
                Sys_UserQuery userQuery = userHandler.GetSys_UserQuery(int.Parse(e.Row.Cells[4].Text));
                if (userQuery != null)
                {
                    e.Row.Cells[4].Text = userQuery.Name;

                    Sys_OrganizationQuery orgQuery = orgHandler.GetSys_OrganizationQuery(userQuery.Org_ID);
                    if(orgQuery != null)
                        e.Row.Cells[2].Text = orgQuery.Name;
                    else
                        e.Row.Cells[2].Text = "";

                    Sys_PostQuery postQuery = postHandler.GetSys_PostQuery(userQuery.Post_ID);
                    if (postQuery != null)
                        e.Row.Cells[3].Text = postQuery.Name;
                    else
                        e.Row.Cells[3].Text = "";

                }

                // 状态
                Enums.PersonalApprovalStatus status = (Enums.PersonalApprovalStatus)int.Parse(e.Row.Cells[8].Text);
                e.Row.Cells[8].Text = Enums.GetPersonalApprovalStatus(status);
                //ImageButton ibtnViewFlow = (ImageButton)e.Row.FindControl("ibtnViewFlow");
                //ibtnViewFlow.Visible = status != Enums.PersonalApprovalStatus.NewAdded;
            }
        }
    }

    protected void gvPerfApproveList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        RefreshDataGridView();
    }

    #endregion

    #region Button
    
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (!ddlStatus.SelectedValue.Equals("0"))
            ViewState["SearchStatus"] = ddlStatus.SelectedValue;
        else
            ViewState["SearchStatus"] = null;

        if (txtPerfDate.Text != null && !"".Equals(txtPerfDate.Text))
            ViewState["SearchPerfDate"] = txtPerfDate.Text;
        else
            ViewState["SearchPerfDate"] = null;

        RefreshDataGridView();
    }

    protected void ApproveButton_Click(object sender, EventArgs e)
    {
            RefreshDataGridView();
    }

    protected void AspNetPager_PageChanged(object src, EventArgs e)
    {
        RefreshDataGridView();
    }

    #endregion

    private void RefreshDataGridView()
    {
        SqlParameter[] parms = null;
        string clause = " 1=1 ";
        ProcessParms(ref clause, ref parms);
        dataBind(clause, parms);
    }

}
